package tenantchannellogic

import (
	"context"

	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/tenant/channel"
	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/tenant/channel"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BankListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBankListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BankListLogic {
	return &BankListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BankListLogic) BankList(in *rpc.BankListRequest) (*rpc.BankListResponse, error) {
	var (
		CommonResp rpc.CommonResp
		bankList   []schema.TenantChannelBank
		err        error
	)

	bankModel := model.NewTenantChannelBankModel(l.ctx, l.svcCtx.Db)
	if in.BankName != "" || in.CardNumber != "" || in.CardHolder != "" {
		bankList, err = bankModel.GetBanksByFilter(in.BankName, in.CardNumber, in.CardHolder)
	} else {
		bankList, err = bankModel.GetAllBank()
	}

	if err != nil {
		CommonResp.Code = xerrors.DBError
		CommonResp.Message = "Database operation error"
		return &rpc.BankListResponse{
			CommonResp: &CommonResp,
		}, err
	}

	var records []*rpc.Bank

	for _, bank := range bankList {
		records = append(records, &rpc.Bank{
			Id:           bank.ID,
			CreatedAt:    bank.CreatedAt,
			UpdatedAt:    bank.UpdatedAt,
			Code:         bank.Code,
			Phone:        bank.Phone,
			MinAmount:    bank.MinAmount,
			MaxAmount:    bank.MaxAmount,
			DailyTimes:   bank.DailyTimes,
			DailyAmount:  bank.DailyAmount,
			RemainTimes:  bank.RemainTimes,
			RemainAmount: bank.RemainAmount,
			VisionLevel:  bank.VisionLevel,
			IsDisplay:    bank.IsDisplay,
			CardNumber:   bank.CardNumber,
			BankNickname: bank.BankNickname,
			BankName:     bank.BankName,
			IfscCode:     bank.IfscCode,
			Email:        bank.Email,
			Province:     bank.Province,
			City:         bank.City,
			BranchBank:   bank.BranchBank,
			IsLimit:      bank.IsLimit,
			CardHolder:   bank.CardHolder,
			Sort:         bank.Sort,
		})
	}

	CommonResp.Message = "Success"
	return &rpc.BankListResponse{
		Records:    records,
		CommonResp: &CommonResp,
	}, nil
}
